package com.x.xiaoshuo.ui.appbar;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

import com.x.mvp.appbar.AppBarBuilder;
import com.x.xiaoshuo.R;


public class SearchAppBarBuilder extends AppBarBuilder {
    EditText searchText;
    View clear;

    boolean clearStyle;

    @Override
    protected View getCenterSpace(LayoutInflater layoutInflater) {
        View centerView = layoutInflater.inflate(R.layout.toolbar_search_edittext, null);
        searchText = (EditText) centerView.findViewById(R.id.search);
        clear = centerView.findViewById(R.id.clear);
        clear.setVisibility(View.GONE);
        if (!clearStyle) {
            searchText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (TextUtils.isEmpty(s)) {
                        clear.setVisibility(View.GONE);
                    } else {
                        clear.setVisibility(View.VISIBLE);
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
            clear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    searchText.setText("");
                }
            });
        }
        return centerView;
    }

    @Override
    protected View getRightSpace(LayoutInflater layoutInflater) {
        View left = layoutInflater.inflate(R.layout.toolbar_sure, null);
        if (clearStyle) {
            left.setVisibility(View.INVISIBLE);
        }
        return left;
    }

    @Override
    protected View getLeftSpace(LayoutInflater layoutInflater) {
        View left = layoutInflater.inflate(R.layout.toolbar_back, null);
        return left;
    }

    public EditText getSearchText() {
        return searchText;
    }

    public void setClearStyle(boolean clearStyle) {
        this.clearStyle = clearStyle;
    }
}
